
<template>
  <div style="height:100%;width:100%;position:relative;overflow: hidden;">
    <div class="pagetop">
      <div class="search-title">快速查询</div>
      <el-input v-model.trim="txtSearch" @input="btnQuery()" placeholder="库位类型代号 | 名称" style="width:200px"
        :disabled="changeFlag"></el-input>
      <div class="search-title">样本库</div>
      <el-select v-model="selCodeno" filterable style="width:150px" @change="btnQuery" ref="refSelCodeno"
        :disabled="changeFlag">
        <el-option v-for="(item, index) in selSmpLibrary_Options" :key="index" :value="item.librid"
          :label="item.librname"></el-option>
      </el-select>
      <div class="top-deal">
        <el-button @click="btnQuery()" icon="el-icon-search" v-has="'PINQUERY'" type="primary">查询</el-button>
        <el-button icon="el-icon-plus" v-has="'PADD'" @click="btnAdd" :disabled="changeFlag">新增</el-button>
        <el-button icon="el-icon-delete" v-has="'PDELETE'" @click="btnDel" :disabled="changeFlag">删除</el-button>
        <el-button icon="el-icon-document" v-has="'PMODIFY'" @click="btnSave" :disabled="!changeFlag">保存</el-button>
        <el-button icon="el-icon-document" v-has="'PMODIFY'" @click="btnCancel" :disabled="!changeFlag">取消</el-button>
      </div>
    </div>
    <div class="pagecenter">
      <rm-layout-right splitcolor="#FFFFFF" movingcolor="#CCFFFF" :splitwidth=5 :fixsize=450>
        <vxe-table :loading="loading" :data.sync="leftTableData" border fit height="auto" header-align="center"
          highlight-current-row highlight-hover-row ref="xTable" resizable show-header-overflow="tooltip"
          show-overflow="tooltip" size="mini" stripe @current-change="CurrentChange" :cell-class-name="CellClassName"
          :row-class-name="RowClassName">
          <vxe-table-column field="librname" title="样本库" width="80" align="center"></vxe-table-column>
          <vxe-table-column field="loctypeno" title="库位类型代码" width="100"></vxe-table-column>
          <vxe-table-column field="loctypename" title="库位类型名称" width="200"></vxe-table-column>
        </vxe-table>
        <template v-slot:fix>
          <div style="width:100%;float:left;height:100%;border:1px solid #ccc;overflow:auto;" id="showbox">
            <el-form :inline="true" @submit.native.prevent label-width="auto" ref="form_bbjlx" :model="detailData">
              <table
                style="width:100%;font-size:12px;white-space: nowrap; padding-top:3px;text-align: left; align:;center;padding:0px 5px 5px 0px">
                <tr>
                  <td style="text-align: right; ">样本库ID</td>
                  <td colspan="3">
                    <el-select v-model="detailData.librid" filterable style="width:300px" ref="input1"
                      @keyup.enter.native="Autofocus('selLibrID')" @change="IsChange" :disabled="true" placeholder="">
                      <el-option v-for="(item, index) in selSmpLibrary_Options" :key="index" :value="item.librid"
                        :label="item.librname"></el-option>
                    </el-select>
                  </td>
                </tr>
                <tr>
                  <td style="color:#F56C6C;text-align: right; ">库位类型代码</td>
                  <td colspan="3">
                    <el-input style="width:300px;" v-model="detailData.loctypeno" @input="IsChange" ref="input1"
                      @change="chkLocTypeNo" @keyup.enter.native="NextFocus(1)" :disabled="disabledNo"></el-input>
                  </td>
                </tr>
                <tr>
                  <td style="color:#F56C6C;text-align: right; ">库位类型名称</td>
                  <td colspan="3">
                    <el-input style="width:300px;" v-model="detailData.loctypename" @input="IsChange" ref="input2"
                      @keyup.enter.native="NextFocus(2)"></el-input>
                  </td>
                </tr>
                <!-- <tr>
                              <td style="text-align: right; ">显示图标</td>
                              <td colspan="3">
                                   <el-upload class="avatar-uploader" action="" :show-file-list="false" :auto-upload="false" :on-change="photoimagechange" :before-upload="beforeAvatarUpload" accept="image/jpeg,image/png">
                                              <img v-if="PhotoImageUrl" :src="PhotoImageUrl" class="avatar">
                                              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                          </el-upload>
                              </td>
                          </tr> -->
              </table>
            </el-form>
          </div>
        </template></rm-layout-right>
    </div>
    <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="提示"
      :visible.sync="bDelVisible" width="500px" height="300px">
      <span class="el-icon-info">确定删除<b>库位:</b><b
          style="color:red">{{ detailData.loctypename }}({{ detailData.loctypeno }})</b>的记录吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="btnDelComfirm">确 定</el-button>
        <el-button @click="btnDelCancel" :autofocus="true">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script type="text/javascript">
import $ from "jquery";
import { Promise } from "q";
import { invalid } from "moment";
import md5 from "js-md5";
import XEUtils from "xe-utils";
export default {
  name: "SMP131",
  data() {
    return {
      loading: false,
      changeFlag: false,
      okFirstLoading: true,
      bDelVisible: false, //删除界面
      disabledNo: true,
      selflag: "1",
      selCodeno: null, //样本库类型代码
      selCodena: "", //样本库类型名称
      txtSearch: "", //查询内容（对 样本库代码、名称进行模糊查询）
      loctypeno: "",
      librid: null, //样本库ID
      actionindex: "M", //M默认 A新增 E修改 D删除
      PhotoImageUrl: "",
      detailData: {
        librid: null,
        loctypeno: "", //库位类型代码
        loctypename: "", //库位类型名称
        displayicon: "" //显示图标
      },
      olddetailData: {
        librid: null,
        loctypeno: "", //库位类型代码
        loctypename: "", //库位类型名称
        displayicon: "" //显示图标
      },
      selRow: {
        librid: null,
        loctypeno: "", //库位类型代码
        loctypename: "", //库位类型名称
        displayicon: "" //显示图标
      },
      addData: [], //新增变色
      modData: [], //修改变色
      leftTableData: [],
      selSmpLibrary_Options: [] //样本库类型
    };
  },
  created() {
    this.ddlSmp_Library(); //初始化样本类型
  },
  mounted() { },
  updated() {
    if (this.okFirstLoading) {
      let currentrow = this.$refs.xTable.getData(0);
      this.$nextTick(() => {
        if (currentrow) {
          this.okFirstLoading = false;
          this.$refs.xTable.setCurrentRow(currentrow);
        }
      });
    }
  },
  methods: {
    /*-----------------------------初始化-----------------------------*/
    //获取样本库列表
    ddlSmp_Library() {
      this.$tool
        .request({
          url: "SMP/SMP1/SMP130",
          method: "post",
          data: {
            action: "q_smp_library",
          },
        })
        .then((res) => {
          this.selSmpLibrary_Options = res
          if (this.selSmpLibrary_Options.length > 0) {
            this.selCodeno = this.selSmpLibrary_Options[0].librid
            this.btnQuery(); //初始化主列表
          }
        })
    },

    /*-----------------------------行改变-----------------------------*/
    CurrentChange({ row, rowIndex }, event) {
      if (this.selflag == "1") {
        this.$nextTick(async () => {
          await this.CurrentChangeEvent(row, rowIndex);
        });
      } else {
        this.$refs.xTable.setCurrentRow(this.selRow);
        return;
      }
    },
    async CurrentChangeEvent(row, rowIndex) {
      this.loctypeno = row.loctypeno;
      this.librid = row.librid
      this.selflag = "0";
      this.CurrentSave()
        .then(() => {
          this.selRow = row;
          this.loctypeno = row.loctypeno;
          this.$refs.xTable.setCurrentRow(row);
          this.$nextTick(async () => {
            await this.DetailQuery();
            this.selflag = "1";
          });
        })
        .catch(ex => {
          this.$refs.xTable.setCurrentRow(this.selRow);
          this.selflag = "1";
        });
    },
    CurrentSave() {
      return new Promise((s, f) => {
        let haschange = false;
        let saveinfo = XEUtils.clone(this.detailData, true);
        if (this.actionindex == "M") {
          //如果是修改
          if (!XEUtils.isEqualWith(this.olddetailData, saveinfo)) {
            //表单被更改
            haschange = true;
          }
        } else if (this.actionindex == "A") {
          //如果是新增
          haschange = true;
        }
        if (saveinfo.loctypeno == "") {
          this.$alert("库位类型代码不可为空！", "提示", { type: "warning" }, {
            confirmButtonText: "确定"
          });
          f();
          this.$refs.input1.focus();
          return false;
        }
        if (saveinfo.loctypename == "") {
          this.$alert("库位类型名称不可为空！", "提示", { type: "warning" }, {
            confirmButtonText: "确定"
          });
          f();
          this.$refs.input2.focus();
          return false;
        }
        if (haschange) {
          this.$nextTick(async () => {
            const res = await this.$tool.request({
              url: "SMP/SMP1/SMP131",
              method: "post",
              data: {
                action: "smp_loctype_addedit",
                data: saveinfo,
                librid: this.selCodeno
              }
            });
            if (res.errcode == "1") {
              this.$message({
                message: "保存成功！",
                type: "success",
                showClose: true,
              });
              this.loctypeno = res.keyid;
              this.changeFlag = false;
              this.disabledNo = true;
              //不是删除操作
              if (this.actionindex == "A") {
                //新增数据成功后的不刷新操作
                saveinfo.loctypeno = this.loctypeno;
                this.detailData.loctypeno = this.loctypeno;
                this.selSmpLibrary_Options.forEach(item => {
                  if (saveinfo.librid == item.librid) {
                    saveinfo.librname = item.librname;
                  }
                });
                this.$refs.xTable.insertAt(saveinfo, -1).then(({ row }) => {
                  this.$refs.xTable.setCurrentRow(row);
                  this.selRow = row;
                });
                if (this.addData.indexOf(this.loctypeno) < 0) {
                  this.addData.push(this.loctypeno);
                }
              } else if (this.actionindex == "M") {
                this.SetToTable(saveinfo);
                if (this.modData.indexOf(this.loctypeno) < 0) {
                  this.modData.push(this.loctypeno);
                }
              }
              this.actionindex = "M";
              s();
            } else {
              this.$message({
                message: "保存失败！" + res.obj,
                type: "error",
                showClose: true,
              })
              f();
            }
          });
        } else {
          this.changeFlag = false;
          s();
        }
      });
    },
    /*-----------------------------按钮类-----------------------------*/
    async btnQuery() {
      this.loading = true;
      this.actionindex = "M"
      this.addData = [];
      this.modData = [];
      try {
        const res = await this.$tool.request({
          url: "SMP/SMP1/SMP131",
          method: "post",
          data: {
            action: "smp_loctype_query",
            keystr: this.txtSearch,
            librid: this.selCodeno
          }
        });
        this.leftTableData = res.RData.Data;
        this.leftTableData.forEach(item => {
          this.selSmpLibrary_Options.forEach(item2 => {
            if (item.librid == item2.librid) {
              item.librname = item2.librname;
            }
          });
        });
        this.okFirstLoading = true;
        this.selRow = null;
        if (res.RData.Data.length > 0) {
          this.selRow = res.RData.Data[0];
          this.loctypeno = res.RData.Data[0].loctypeno;
          this.librid = res.RData.Data[0].librid;
        } else {
          this.loctypeno = "";
          this.librid = null;
          this.detailData = {};
          this.PhotoImageUrl = "";
        }
        this.loading = false;
        if (this.loctypeno != "" && this.librid != null) {
          await this.DetailQuery();
        }
        this.changeFlag = false;
        this.disabledNo = true;
      } catch (e) {
        this.loading = false;
        this.$message({
          message: e.message,
          type: "warning",
          showClose: true,
        })
      }
    },
    async DetailQuery() {
      console.log("🚀 ~ file: SMP131.vue ~ line 352 ~ DetailQuery ~ this.librid", this.librid)
      try {
        const res = await this.$tool.request({
          url: "SMP/SMP1/SMP131",
          method: "post",
          data: {
            action: "smp_loctype_query_byid",
            loctypeno: this.loctypeno,
            librid: this.librid
          }
        });
        this.detailData = res.Data[0];
        this.olddetailData = XEUtils.clone(this.detailData, true);
      } catch (e) {
        this.$message.warning(e.message);
        this.$message({
          message: e.message,
          type: "warning",
          showClose: true,
        })
      }
    },
    btnAdd() {
      if (this.selCodeno != null) {
        this.changeFlag = true;
        this.disabledNo = false;
        this.actionindex = "A";
        this.$refs.input1.focus();
        this.detailData = {
          librid: this.selCodeno,
          loctypeno: "",
          loctypename: "",
          displayicon: ""
        };
      } else {
        this.$message({
          message: "请您先选择对应的样本库。",
          type: "warning",
          showClose: true,
        })
        this.$nextTick(() => {
          this.$refs.refSelCodeno.focus();
          return false;
        });
      }
      this.$nextTick(() => {
        this.$refs.input1.focus();
      });
    },
    btnDel() {
      if (this.detailData.loctypeno == "") {
        this.$message({
          message: "请先选择一条数据！",
          type: "warning",
          showClose: true,
        })
        return false;
      }
      if (this.selCodeno == null) {
        this.$message({
          message: "请先选择所属的样本库。",
          type: "warning",
          showClose: true,
        })
        return false;
      }
      this.bDelVisible = true;
    },
    btnDelCancel() {
      this.bDelVisible = false;
      this.$message({
        type: "info",
        message: "已取消删除"
      });
    },
    btnDelComfirm() {
      this.bDelVisible = false;
      let that = this;
      this.$tool
        .request({
          url: "SMP/SMP1/SMP131",
          method: "post",
          data: {
            action: "smp_loctype_delete",
            loctypeno: this.detailData.loctypeno,
            librid: this.detailData.librid
          }
        })
        .then(res => {
          if (res == "1") {
            this.$message({
              message: "删除成功！",
              type: "success",
              showClose: true,
            });
            this.actionindex = "M";
            //是删除操作
            var delrow = that.$refs.xTable.getCurrentRow();
            if (delrow) {
              var alld = that.$refs.xTable.getTableData().fullData;
              var rowindex = alld.indexOf(delrow);
              that.$refs.xTable.remove(delrow);
              setTimeout(async () => {
                let havedata = that.$refs.xTable.tableData;
                if (havedata.length > 0) {
                  if (rowindex >= havedata.length) rowindex = havedata.length - 1;
                  let selectrow = havedata[rowindex];
                  that.$refs.xTable.setCurrentRow(selectrow);
                  that.loctypeno = selectrow.loctypeno;
                  await this.DetailQuery();
                  that.$refs.xTable.scrollToRow(selectrow);
                }
              }, 5);
            }
          } else {
            this.$message({
              message: "删除失败！" + res,
              type: "error",
              showClose: true,
            })
          }
        })
        .catch(e => {
          this.$message({
            message: "删除失败！" + e,
            type: "error",
            showClose: true,
          })
        });
    },
    btnSave() {
      let that = this;
      let gData = XEUtils.clone(that.detailData, true);
      if (this.actionindex == "M") {
        //无数据时
        if (this.loctypeno == "") {
          this.$alert("请您通过新增按钮来添加数据", "提示", { type: "warning" }, {
            confirmButtonText: "确定",
          })
          this.btnCancel();
          return false;
        }
        if (this.selCodeno == null) {
          this.$alert("请先选择对应的样本库。", "提示", { type: "warning" }, {
            confirmButtonText: "确定",
          })
          this.$nextTick(() => {
            this.$refs.refSelCodeno.focus();
          });
          this.btnCancel();
          return false;
        }
      }
      if (gData.loctypeno == "") {
        this.$alert("库位类型代码不可为空！", "提示", { type: "warning" }, {
          confirmButtonText: "确定"
        });
        this.$refs.input1.focus();
        return false;
      }
      if (gData.loctypename == "") {
        this.$alert("库位类型名称不可为空！", "提示", { type: "warning" }, {
          confirmButtonText: "确定"
        });
        this.$refs.input2.focus();
        return false;
      }
      this.$tool
        .request({
          url: "SMP/SMP1/SMP131",
          method: "post",
          data: {
            action: "smp_loctype_addedit",
            data: gData,
            librid: this.selCodeno
          }
        })
        .then(res => {
          if (res.errcode == "1") {
            that.$message({
              message: "保存成功！",
              type: "success",
              showClose: true,
            });
            this.loctypeno = res.keyid;
            this.changeFlag = false;
            this.disabledNo = true;
            //不是删除操作
            if (this.actionindex == "A") {
              gData.loctypeno = this.loctypeno;
              this.selSmpLibrary_Options.forEach(item => {
                if (gData.librid == item.librid) {
                  gData.librname = item.librname;
                }
              });
              this.detailData.loctypeno = this.loctypeno;
              this.$refs.xTable.insertAt(gData, -1).then(({ row }) => {
                this.$refs.xTable.setCurrentRow(row);
                this.selRow = row;
              });
              if (this.addData.indexOf(this.loctypeno) < 0) {
                this.addData.push(this.loctypeno);
              }
            } else if (this.actionindex == "M") {
              this.SetToTable(gData);
              if (this.modData.indexOf(this.loctypeno) < 0) {
                this.modData.push(this.loctypeno);
              }
            }
            this.selRow = this.$refs.xTable.getCurrentRow();
            this.actionindex = "M";
            setTimeout(async () => {
              if (this.selRow) {
                await this.DetailQuery(); //比较保存后值是否发生改变
                this.$refs.xTable.setCurrentRow(this.selRow);
                this.$refs.xTable.scrollToRow(this.selRow);
              }
            }, 5);
          } else {
            this.actionindex = that.actionindex;
            this.$message({
              message: "保存失败！" + res.obj,
              type: "error",
              showClose: true,
            })
          }
        })
        .catch(e => {
          that.$message.error(e);
          this.$message({
            message: e,
            type: "error",
            showClose: true,
          })
        });
    },
    async btnCancel() {
      this.actionindex = "M";
      this.changeFlag = false;
      this.disabledNo = true;
      let row = this.$refs.xTable.getCurrentRow();
      this.loctypeno = row.loctypeno;
      await this.btnQuery();
    },
    btnPrint() { },
    btnExport() { },
    /*-------------------------------其它-------------------------------*/
    chkLocTypeNo() {
      this.$tool
        .request({
          url: "SMP/SMP1/SMP131",
          method: "post",
          data: {
            action: "chkloctypeno",
            loctypeno: this.detailData.loctypeno,
            librid: this.detailData.librid
          }
        })
        .then(res => {
          if (res == "1") {
            this.$warning("入库条件代号已存在，请重新填写。");
            this.$refs.input1.focus();
          }
        })
        .catch(e => {
          this.$alert(e);
        });
    },
    IsChange() {
      this.changeFlag = true;
    },
    NextFocus(index) {
      if (index > 3) return false;
      var that = this;
      var focusIndex = index + 1;
      setTimeout(function () {
        that.$refs["input" + focusIndex].focus();
      }, 1);
    },
    async SetToTable(obj) {
      this.$nextTick(() => {
        this.selRow.loctypeno = obj.loctypeno;
        this.selRow.loctypename = obj.loctypename;
        this.selRow.librid = obj.librid;
        this.selRow.displayicon = obj.displayicon;
        this.olddetailData = XEUtils.clone(this.selRow, true);
        this.PhotoImageUrl = "";
      });
    },
    photoimagechange(file) {
      let that = this;
      that.changeflag = true;
      this.PhotoImageUrl = URL.createObjectURL(file.raw);
      var reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = function () {
        that.detailData.displayicon = reader.result.toString();
        // that.detailData.photofiletype = file.name.split(".")[1].toString();
      };
      reader.onerror = function (error) {
        console.log("Error: ", error);
      };
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message({
          message: "上传头像图片只能是 JPG 格式!",
          type: "warning",
          showClose: true,
        })
      }
      if (!isLt2M) {
        this.$message({
          message: "上传头像图片大小不能超过 2MB!!",
          type: "warning",
          showClose: true,
        })
      }
      return isJPG && isLt2M;
    },
    /*------------------------------Class------------------------------*/
    RowClassName({ row, rowIndex }) {
      if (this.addData.indexOf(row.loctypeno) > -1) {
        return "rm-new";
      }
      if (this.modData.indexOf(row.loctypeno) > -1) {
        return "rm-modify";
      }
    },
    CellClassName({ columnIndex, row }) { }
  }
};
</script>

<style scoped>
.pagetop {
  width: 100%;
  height: 35px;
  display: -webkit-box;
  -webkit-box-pack: left;
  -webkit-box-align: center;
  border: 1px solid #ccc;
  position: absolute;
  font-size: 12px;
  z-index: 99;
  overflow-x: auto;
  white-space: nowrap;
}

.pagetop .top-table {
  float: right;
}

.top-deal {
  right: 5px;
  position: absolute;
  top: 5px;
  display: flex;
  align-items: center;
}

.search-title {
  margin: 0 5px 0 20px;
  font-size: 12px;
}

.pagecenter {
  position: absolute;
  top: 40px;
  width: 100%;
  left: 0;
  bottom: 0px;
  overflow: auto;
}

table {
  font-size: 12px;
  border-collapse: separate;
  border-spacing: 5px;
}

.table1style tr td {
  padding: 0px 2px 0px 5px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 18px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

.avatar {
  width: 50px;
  height: 50px;
  display: block;
}

::v-deep .el-input.is-disabled .el-input__inner {
  color: #606266;
  cursor: not-allowed;
}

::v-deep  .vxe-table .vxe-body--column.col-orange {
  background-color: #f8f8f8;
}

::v-deep .el-input--suffix .el-input__inner {
  padding-right: 5px;
}

::v-deep .el-textarea__inner {
  padding: 5px;
  cursor: default;
}

::v-deep  tr.vxe-body--row.row--current {
  color: #000000;
  font-weight: bold;
}</style>
